package routing.googleadapter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * Gets a route between two coords from Google
 * 
 * @author Alexander Münch (sialmuen)
 */
public class GoogleRoutingAnfrageController {
	private static final long serialVersionUID = 1L;
	
	static Logger logger = Logger.getLogger(GoogleRoutingAnfrageController.class.toString());

     /* gets the route. This method may be called be other services!
     * 
     * @param from
     * @param to
     * @return String KML data
     */
	
    public static String getGoogleRouteAsKML(String from, String to) {
    	String response = null;
    	String url = getURL(from, to);
    	response = queryWebpage(url);

    	return response;
    }
    
    private static String queryWebpage(String targetURL) {
    	return queryWebpage(targetURL, false);
    }
    
    /**
	 * calls the requested URL and returns its source
	 * @param zielUrl URL die aufgerufen werden soll
	 * @param mitNewlines true wenn newlines mitgelesen werden sollen, sonst false
	 * @return
	 */
    // FIXME: copied from BahnRoute2.java - duplicate code
	private static String queryWebpage(String targetURL, boolean mitNewlines){
		// logger.log(Level.INFO, "Requesting URL: " + targetURL.toString());
		System.out.println("Requesting URL: " + targetURL);
		String xml = null;
		String inputLine;
		StringBuffer content = new StringBuffer();
		try {
			URL url = new URL(targetURL.toString());
			URLConnection uc = url.openConnection();
			BufferedReader googleIn = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
			String b;
			
			while ((b = googleIn.readLine()) != null) {
				/*
				content.append(inputLine);
				if (mitNewlines) content.append("\n");
				*/
				
				content.append(b.trim());
			}
			
			xml = content.toString();
			System.out.println(uc.getURL() + " response: " + xml);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//logger.log(Level.INFO,"Response: " + xml);
		//System.out.println("Response: " + xml);
		return xml;
	}
    
    /**
     * returns a URL for querying Google for a route
     * example: http://maps.google.com/maps?oe=UTF-8&output=kml&saddr=Nürnberg Hauptbahnhof&daddr=Nürnberg Flughafen&dirflg=w
     * 
     * @see http://mapki.com/wiki/Google_Map_Parameters
     * 
     * @param from
     * @param to
     * @return URL
     */
    private static String getURL(String from, String to) {
    	String url = "https://maps.googleapis.com/maps/api/directions/xml";
    	try {
			url += "?origin=\"" + URLEncoder.encode(from, "UTF-8");
	    	url += "\"&destination=\"" + URLEncoder.encode(to, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	url += "\"&sensor=false&mode=walking&language=de";
    	
    	logger.log(Level.INFO, url);
    	return url;
    }
    

	/**
	 * example: http://faui8183.informatik.uni-erlangen.de:8080/Roserv/route/google?from=49.432,11.000&to=49.532,11.129
	 * 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(String from, String to) {
		// ask Google for the route and convert it to JSON
		String kmlRoute = getGoogleRouteAsKML(from, to);
		KmlParser kmlParser = new KmlParser(kmlRoute);
		String waypointsArray = kmlParser.toJSON();
		
		String output = new String("{\"status\":\"OK\", \"data\":[ \"waypoints\": " + waypointsArray + "]}");
		System.out.println(output);
	}
	
	/**
	 * debug testing main
	 * @param args unused
	 */
	public static void main(String [] args){
		String from = "49.432,11.000";
		String to = "49.532,11.129";
		
		// ask Google for the route and convert it to JSON
		String kmlRoute = GoogleRoutingAnfrageController.getGoogleRouteAsKML(from, to);
		KmlParser kmlParser = new KmlParser(kmlRoute);
		String waypointsArray = kmlParser.toJSON();
		
		String output = new String("{\"status\":\"OK\", \"data\":[ \"waypoints\": " + waypointsArray + "]}");
		System.out.println(output);
	}

}
